//
//  TJEmotionManager.swift
//  表情键盘
//
//  Created by 唐后能 on 16/4/21.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

let numberOfPage = 20  // 每页表情的个数.

let rowNumberOfPage = 3 //表情的行数.

let culomNumberOfPage = 7 //表情的列数.

let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil) //mainBunle的路径.

private let emotionSavePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/emotion.plist")

// MARK:  专门来处理(加载/保存)表情模型和表情包模型
class TJEmotionManager: NSObject {

    // 创建表情模型管理单例.
    static let shareEmotionManager:TJEmotionManager = TJEmotionManager()
    
    // 表情包模型数组-->外界通过该属性来访问所有表情包/表情.
    // 文件存在磁盘中,通过懒加载一次就好了,如果多次加载,很耗性能.
    lazy var emotionPackages:[TJEmotionPackage] = self.loadEmotionPackages()
    
    
    // 加载所有表情包.
    private func loadEmotionPackages()->[TJEmotionPackage]{
    
        // 加载最近的空表情包.
        let recentPackage = TJEmotionPackage(id: "", group_name_cn: "最近", emoticons:loadEmotion())
        // 加载其它表情包.
        let defaultPackage = loadEmotionPackage("com.sina.default")
        let emojiPackage = loadEmotionPackage("com.apple.emoji")
        let lxhPackage = loadEmotionPackage("com.sina.lxh")
        return [recentPackage,defaultPackage,emojiPackage,lxhPackage]
    }
    
    // 加载单个表情包.->需传入文件夹名称.
    private func loadEmotionPackage(id:String)->TJEmotionPackage{
    
        // 拼接路径.
//        let fullPath = bundlePath! + "/" + id + "/" + "info.plist"
        let fullPath = "\(bundlePath!)/\(id)/info.plist"
//        print("\(fullPath)")
        // 读取plist文件.
        let infoDict = NSDictionary(contentsOfFile: fullPath)
        
        // 给表情包属性赋值.
        let group_name_cn = infoDict!["group_name_cn"] as! String
        
        var emotions:[TJEmotion] = []
        if let emotionArr = infoDict!["emoticons"] as? [[String:String]]  {
        
            for dict in emotionArr {
                let emotion = TJEmotion(dict: dict,id: id)
                emotions.append(emotion)
            }
        }
        // 创建并返回表情包模型.
        return TJEmotionPackage(id: id, group_name_cn: group_name_cn, emoticons: emotions)
    }
    
    // 将表情添加到最近表情页面.
    func addEmotionToRecent(emotion:TJEmotion) {
        
        // 1,添加表情到最近表情页中.
         // 1.1,先判断是否点击了重复表情.
        for emt in emotionPackages[0].pageEmotions[0] {
         
            if (emotion.chs != nil && emt.chs == emotion.chs) || (emotion.code != nil && emt.code == emotion.code) {
            
                // 找出该相同的表情在数组中的位置,从数组中删除.
                let index = emotionPackages[0].pageEmotions[0].indexOf(emt)
                emotionPackages[0].pageEmotions[0].removeAtIndex(index!)
            }
        }
        // 1.2,将点击的表情添加到最近表情页数组中,插入到最前面.
        // 获取最近表情页.该方式创建了新的数组,在新数组中添加元素后,还要将新数组赋值给最近表情也数组->Swift的数组是指传递.
        //        var recentPackageEmotion:[TJEmotion] = emotionPackages[0].pageEmotions[0]
        //        recentPackageEmotion.append(emotion)
        emotionPackages[0].pageEmotions[0].insert(emotion, atIndex: 0)
        
        // 1.3判断是否已经超出20个表情.
        if emotionPackages[0].pageEmotions[0].count > 20 {
        
            emotionPackages[0].pageEmotions[0].removeLast()
        }
        
        // 2,将最近表情模型页保存到沙盒中.
        saveEmotion()
        
//        print("emotionPackages[0].pageEmotions[0]:\(emotionPackages[0].pageEmotions[0])")
    }
    
    // 保存最近表情模型页.
    private func saveEmotion(){
    
        NSKeyedArchiver.archiveRootObject(emotionPackages[0].pageEmotions[0], toFile: emotionSavePath!)
    }
    
    // 加载最近表情模型页.
    private func loadEmotion()->[TJEmotion]{
    
        if let recentEmotions = NSKeyedUnarchiver.unarchiveObjectWithFile(emotionSavePath!) as? [TJEmotion] {
         print("最近表情保存路径:\(emotionSavePath!)")
            return recentEmotions
        }else {
        
            return []
        }
    }
}
